<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6" :xs="24">
            <el-form-item label="账号">
              <el-input v-model="page.account"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="状态">
              <el-select style="width: 100%;" v-model="page.status" clearable>
                <el-option :value="1" label="启用"></el-option>
                <el-option :value="0" label="禁用"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="6" :xs="24">-->
          <!--            <el-form-item label="电话">-->
          <!--              <el-input v-model="page.phone"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="primary" icon="el-icon-plus" @click="addsStaff">添加员工</el-button>
    </div>
    <Table :tableColumn="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #status="{row}">
        <el-switch :model-value="row.status === 1" @change="staffChange(row)"></el-switch>
      </template>
      <template #appName="{row}">
        <el-tag style="margin: 0 10px 10px 0" :disable-transitions="true" v-for="item in (row.userBindAppList || [])"
                v-show="item.isBind === 1" :key="item.appid">{{ item.appName }}
        </el-tag>
      </template>
      <template #marketingSwitch="{row}">
        <el-switch :model-value="row.marketingSwitch === 1" @change="markerStatusChange(row)"></el-switch>
      </template>
      <template #handle="{row}">
        <el-button type="text" @click="editStaff(row)">编辑</el-button>
        <el-button type="text" @click="resetPassword(row)">重置密码</el-button>
        <el-button type="text" @click="deleteStaff(row)">删除</el-button>
      </template>
    </Table>
    <Dialog v-model="visible.isShow" @close="clearForm"
            @confirm="staffConfirm"
            :title="visible.title" @cancel="visible.isShow = false">
      <el-form label-width="80px" ref="formRef" :model="form" :rules="rulesForm">
        <el-form-item label="账号" prop="account">
          <el-input :disabled="visible.type === 'edit'" v-model="form.account"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"/>
        </el-form-item>
        <el-form-item label="选择角色" prop="rid" v-if="visible.type !== 'edit'">
          <el-select v-model="form.rid">
            <el-option v-for="item in selectRole" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定贷超APP" prop="appIdList" label-width="120px">
          <el-select v-model="form.appIdList" style="width: 100%" clearable multiple>
            <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                       :value="item.appId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="visible.type !== 'edit'">
          <el-radio v-model="form.status" :label="1">启用</el-radio>
          <el-radio v-model="form.status" :label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs} from 'vue'
import {
  fetchStaffList,
  insertStaff,
  updateStaff,
  updateStatusStaff,
  resetStaffPassword,
  fetchRoleType,
  stafffMarketingSwitch,
  deleteStaff
} from '@/api/authority'
import {changeMenuStatus, selectProductList} from "@/api";
import {ElMessage, ElMessageBox} from "element-plus";

const tableColumn = [
  {label: '名称', align: 'center', prop: 'name', minWidth: 100},
  {label: '账号', align: 'center', prop: 'account', minWidth: 150},
  {label: '电话', align: 'center', prop: 'phone', minWidth: 150},
  {label: '角色类型', align: 'center', prop: 'roleName', minWidth: 150},
  {label: '已绑贷超APP', align: 'center', slot: 'appName', minWidth: 150},
  {label: '状态', align: 'center', slot: 'status', prop: 'status', minWidth: 150},
  {label: '营销开关', align: 'center', slot: 'marketingSwitch', prop: 'marketingSwitch', minWidth: 150},
  {label: '创建人', align: 'center', prop: 'inputName', minWidth: 150},
  {label: '创建时间', align: 'center', prop: 'creationTime', minWidth: 150},
  {label: '操作', align: 'center', slot: 'handle', fixed: 'right', minWidth: 100}
]
export default {
  name: "StaffManage",
  setup() {
    const formRef = ref(null)
    const state = reactive({
      tableData: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      visible: {
        isShow: false,
        type: 'add',
        title: ''
      },
      rulesForm: {
        account: [
          {required: true, message: '请输入员工账号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入员工姓名', trigger: 'blur'}
        ],
        rid: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ],
        appIdList: [
          {required: true, message: '请选择贷超APP', trigger: 'change'}
        ]
      },
      form: {
        account: null,
        name: null,
        phone: null,
        rid: null,
        appIdList: [],
        status: 1
      },
      selectRole: [],
      productList: []
    })
    const methods = {
      async getTableData() {
        const res = await fetchStaffList(state.page)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
        }
        methods.getTableData()
      },
      resetPassword({systemUserId}) {
        ElMessageBox.confirm('确认重置密码?', '提示', {
          type: 'warning',
        }).then(async () => {
          const res = await resetStaffPassword({
            systemUserId,
          })
          if (res.code === 200) {
            ElMessage.success({
              message: '操作成功'
            })
            methods.getTableData()
          }
        }).catch(() => {
        });
      },
      editStaff(row) {
        state.form = {...row}
        state.form.appIdList = row.userBindAppList.filter(item => item.isBind === 1).map(item => item.appId)
        state.visible = {
          isShow: true,
          title: '编辑员工',
          type: 'edit'
        }
        methods.getRoleType()
      },
      clearForm() {
        formRef.value.resetFields()
        state.form = {
          account: null,
          name: null,
          phone: null,
          rid: null,
          status: 1,
          appIdList: []
        }
      },
      async getRoleType() {
        const res = await fetchRoleType()
        if (res.code === 200) {
          state.selectRole = res.data
        }
      },
      staffChange({systemUserId, status}) {
        ElMessageBox.confirm('确认进行此操作?', '提示', {
          type: 'warning',
        }).then(async () => {
          const res = await updateStatusStaff({
            id: systemUserId, status: status === 0 ? 1 : 0
          })
          if (res.code === 200) {
            ElMessage.success({
              message: '操作成功'
            })
            methods.getTableData()
          }
        }).catch(() => {
        });
      },
      markerStatusChange({systemUserId, marketingSwitch}) {
        ElMessageBox.confirm('确认进行此操作?', '提示', {
          type: 'warning',
        }).then(async () => {
          const res = await stafffMarketingSwitch({
            id: systemUserId,
            marketingSwitch: marketingSwitch === 1 ? 0 : 1
          })
          if (res.code === 200) {
            ElMessage.success({
              message: '操作成功'
            })
            methods.getTableData()
          }
        }).catch(() => {
        });
      },
      staffConfirm() {
        formRef.value.validate(async v => {
          if (v) {
            const isAdd = state.visible.type === 'add'
            const api = ((params) => isAdd ? insertStaff(params) : updateStaff(params))
            const res = await api(state.form)
            if (res.code === 200) {
              ElMessage.success(isAdd ? '添加成功' : '编辑成功')
              state.visible.isShow = false
              methods.getTableData()
            }
          }
        })
      },
      addsStaff() {
        state.visible = {
          isShow: true,
          title: '添加员工',
          type: 'add'
        }
        methods.getRoleType()
      },
      async deleteStaff({systemUserId}) {
        ElMessageBox.confirm('确认删除此员工?', '提示', {
          type: 'warning',
        }).then(async () => {
          const res = await deleteStaff({
            status: 2,
            id: systemUserId
          })
          if (res.code === 200) {
            ElMessage.success({
              message: '删除成功'
            })
            methods.getTableData()
          }
        }).catch(() => {

        });
      },
      getSelect() {
        selectProductList().then(res => {
          if (res.code === 200) {
            state.productList = res.data
          }
        })
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getSelect()
    })
    return {
      formRef,
      tableColumn,
      ...toRefs(state),
      ...methods
    }
  }
}
</script>

<style scoped>

</style>
